package com.example.webdownloadserver.util;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * 
 * <p>
 * 自定义JSON工具类
 * </p>
 * @title JsonUtils.java
 * @package com.dnkj.download.task.util 
 * @author ying.xiao
 * @version 0.1 2020年12月5日
 */
public class JsonUtils {
	private JsonUtils() {}
	
	private static ObjectMapper mapper = new ObjectMapper();
	
	static{
		mapper.getDeserializationConfig().without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
		.with(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
	}
	
	public static <T> T parser(String content,  TypeReference<T> t) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(content, t);
	}
	
	public static <T> T parser(String content,Class<T> cls) throws JsonParseException, JsonMappingException, IOException{
		return mapper.readValue(content, cls);
	}
	
	public static String writeValueAsString (Object value) throws JsonProcessingException {
		return mapper.writeValueAsString(value);
	}
	
	
	public static String alibabaJsonString(Object obj){
		return com.alibaba.fastjson.JSON.toJSONString(obj
				,SerializerFeature.WriteMapNullValue
				,SerializerFeature.WriteNullStringAsEmpty
				,SerializerFeature.WriteNullListAsEmpty);
	}

	public static String alibabaNoJsonString(Object obj){
		return com.alibaba.fastjson.JSON.toJSONString(obj);
	}
	
}
